import {
  Notification
} from "element-ui";
import { v4 as uuidv4 } from 'uuid';
let id = localStorage.getItem("userId");
var socket = null; //实例对象
var lockReconnect = false; //是否真正建立连接
var timeout = 20 * 1000; //20秒一次心跳
var timeoutObj = null; //心跳倒计时
var resetObj = null;//重连
var resetTime = 5 * 1000;//每5秒重连一次

const initWebSocket = async () => {
  let uuid = localStorage.getItem("uuid");
  if(!uuid) {
    uuid = uuidv4();
    localStorage.setItem('uuid',uuid);
  }

  if ("WebSocket" in window) {
    // socket = new WebSocket('ws://112.124.41.65:8084/prod-api/websocket/message/' + id);
    socket = new WebSocket('ws://localhost:8080/websocket/message/' + id);
    // socket = new WebSocket('wss://zx.amyoux.com/prod-api/websocket/message/' + id);
    socket.onerror = webSocketOnError;
    socket.onmessage = webSocketOnMessage;
    socket.onclose = closeWebsocket;
    socket.onopen = openWebsocket;
  } else {
    Notification.error({
      title: "错误",
      message: "您的浏览器不支持websocket，请更换Chrome或者Firefox",
    });
  }
}

//建立连接
const openWebsocket = (e) => {
  start();
}

const start = () => {
  // 重连对象，重连成功，清除重连倒计时
  resetObj && clearInterval(resetObj);

  //开启心跳
  timeoutObj = setInterval(function () {
    console.log('连接成功，' + timeout + 'ms检测一次');

    // 如果连接成功 重置报错控制
    lockReconnect = false;

    //这里发送一个心跳，后端收到后，返回一个心跳消息
    if (!socket.readyState == 1) {
      // 重连 清楚定时
      timeoutObj && clearInterval(timeoutObj);

      //重连
      resetObj = clearInterval(() => {
        initWebSocket();
      }, resetTime)
    }
  }, timeout);
}

const webSocketOnError = (e) => {
  console.log('发生错误，即将重连...');
  if (lockReconnect) {
    return;
  }
  // 错误只能进来一次 因为已经去执行重连操作了
  lockReconnect = true;

  // 重连
  openWebsocket();
}

//服务器返回的数据
const webSocketOnMessage = (e) => {
  if (e.data == '连接成功') return;
  console.log('发送成功');

  window.dispatchEvent(new CustomEvent('myEvent', {
    detail: {
      message: e.data
    }
  }))
}

// 关闭回调
const closeWebsocket = (e) => {
  close();
}

//断开连接
const close = () => {
  socket.close();
}

//具体问题具体分析,把需要用到的方法暴露出去
export default {
  initWebSocket,
  close
};
